package com.savitar.account.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.savitar.account.dao.AccountMapper;
import com.savitar.account.entity.Account;
import com.savitar.common.annotation.Create;
import com.savitar.common.annotation.Update;
import com.savitar.common.enums.HttpStatus;
import com.savitar.common.vo.ResultBean;
import com.savitar.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * (Account)服务接口
 *
 * @author Savitar
 * @since 2021-05-14 16:07:46
 */
@Service
public class AccountService extends ServiceImpl<AccountMapper, Account> {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private AccountMapper mapper;

    public ResultBean login(String username, String password) {
        UserDetails userDetails = loadUserByUsername(username);
        if (userDetails == null) {
            return ResultBean.err(HttpStatus.ACCOUNT_NOT_EXIST.getCode(), HttpStatus.ACCOUNT_NOT_EXIST.getDesc());
        }
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            return ResultBean.err(HttpStatus.USERNAME_OR_PASSWORD_ERR.getCode(), HttpStatus.USERNAME_OR_PASSWORD_ERR.getDesc());
        }

        //将当前登陆用户对象存入security
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails, null
        );
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        String token = tokenUtil.generateToken(userDetails);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("tokenHead", tokenHead);
        return ResultBean.ok("登陆成功", result);
    }

    public Account loadUserByUsername(String username) {
        return lambdaQuery().eq(Account::getUsername, username).one();
    }

    public Page<Account> page(Integer pageNum, Integer pageSize, String _username, String _name) {
        IPage<Account> page = new Page<Account>(pageNum, pageSize) {
            private String username = _username;
            private String name = _name;
        };
        return mapper.page(page);
    }

    @Create
    public Account create(Account createVo) throws Exception {
        Integer count = lambdaQuery().eq(Account::getUsername, createVo.getUsername()).count();
        if (count > 0) {
            throw new Exception("用户名已存在");
        }
        createVo.setPkId(IdUtil.simpleUUID());
        String encodePass = passwordEncoder.encode(createVo.getPassword());
        createVo.setPassword(encodePass);
        createVo.insert();
        return createVo;
    }

    @Update
    public Account update(Account updateVo) throws Exception {
        Account account = lambdaQuery().eq(Account::getUsername, updateVo.getUsername()).one();
        if (account != null && !account.getPkId().equals(updateVo.getPkId())) {
            throw new Exception("用户名已存在");
        }
        updateVo.updateById();
        return updateVo;
    }

    public Account deleteById(String id) {
        Account one = lambdaQuery().eq(Account::getPkId, id).one();
        one.deleteById();
        return one;
    }

}